package ru.payment.wm.impl;

import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * User: sergey
 * Date: 14.04.2009
 * Time: 23:21:46
 *
 */
public abstract class XmlObject<N extends Node> implements Serializable {
  private static final long serialVersionUID = -2992582831675274039L;
  private OutputFormat _prettyFormat = OutputFormat.createPrettyPrint();
  private N node;
  private SimpleDateFormat sdf = new SimpleDateFormat();

  public XmlObject(N n) {
    node = n;
  }

  protected N getObjectNode() {
    return node;
  }

  protected String getObjectNodeName() {
    return node.getName();
  }

  protected String selectNodeValueAsString(String path, String defValue) {
    Node node = getObjectNode().selectSingleNode(path);
    return node!=null?node.getText():defValue;
  }

  protected int selectNodeValueAsInt(String path, int defValue) {
    Node node = getObjectNode().selectSingleNode(path);
    return node!=null?Integer.parseInt(node.getText()):defValue;
  }

  protected long selectNodeValueAsLong(String path, long defValue) {
    Node node = getObjectNode().selectSingleNode(path);
    return node!=null?Long.parseLong(node.getText()):defValue;
  }

  protected float selectNodeValueAsFloat(String path, float defValue) {
    Node node = getObjectNode().selectSingleNode(path);
    return node!=null?Float.parseFloat(node.getText()):defValue;
  }

  protected double selectNodeValueAsDouble(String path, double defValue) {
    Node node = getObjectNode().selectSingleNode(path);
    return node!=null?Double.parseDouble(node.getText()):defValue;
  }

  protected Date selectNodeValueAsDate(String path, String pattern) {
    Node node = getObjectNode().selectSingleNode(path);
    sdf.applyPattern(pattern);
    try {
      return node!=null?sdf.parse(node.getText()):null;
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }
  }

  public String asXml() {
    return getObjectNode().asXML();
  }

  public String asPrettyXml() {
    try {

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      XMLWriter writer = new XMLWriter(baos, _prettyFormat);
      writer.write(getObjectNode());
      writer.close();

      return baos.toString();

    } catch (IOException ex) {
      return "XML processing error. " + ex.getMessage();
    }
  }

}
